const fs = require('fs');

var servername = LB.CONFIG.global.server_name;
var ws_addr = LB.CONFIG.global.ws_listen;
var ws_passwd = LB.CONFIG.global.ws_password;
LB.ws_send = new LB.HELPER.WSF(servername , ws_addr , LB.HELPER.MD5(ws_passwd).substring(0,16) , LB.HELPER.MD5(ws_passwd).substring(16,32));

function ws_pre_proc(srv,content){
    var server = LB.ws_send;
    switch(JSON.parse(content).type){
        default:
            LB.log.error('[WebSocket]',`未知的数据包类型:${pack.type}`);
        break;

        case "encrypted":
            try{
                var TempData = LB.HELPER.AES.decrypt(server.k , server.iv , JSON.parse(content).params.raw)
            }catch(err){
                LB.log.error('[WebSocket] 异常信息：'+err.message+'（检查通信密钥是否填写正确？）');
                return;
            };

            data_proc(srv,TempData)
        break;

        case "pack":
            data_proc(srv,content)
        break;
    }
}

function data_proc(srv,str){
    var data = JSON.parse(str);
    //LB.log.info('[WebSocket] <Group>',`<- <${srv}> (event:${data.cause})`);
    let moblist = JSON.parse(fs.readFileSync('./config/mobs.json'))
    let cause = data.cause
    let player = data.params.sender
    let content = data.params.text
    let result = data.params.result
    let mobname = data.params.mobname

    switch(cause){
        case "join":
            LB.bot.toChatGroup(LB.HELPER.MSG.getGameEvent("player_join",srv,player))
        break;

        case "left":
            LB.bot.toChatGroup(LB.HELPER.MSG.getGameEvent("player_left",srv,player))
        break;

        case "chat":
            if(LB.CONFIG.global.features.chat_forward != true){
                return
            }
            LB.bot.toChatGroup(LB.HELPER.MSG.getGameEvent("player_chat",srv,player,content))
        break;

        case "mobdie":
            if(LB.CONFIG.global.features.player_die_nofication != true){
                return
            }
            for(k in moblist){
                if(data.params.srctype == k){
                    var mob_tr = moblist[k]
                }
            }
            if(mobname == data.params.mobtype && data.params.srctype != 'unknown'){
                LB.bot.toChatGroup(LB.HELPER.MSG.getGameEvent("player_kill_by_mobs",srv,mobname,mob_tr))
                LB.log.debug(mob_tr)
            }
            else if(mobname != ''){
                LB.bot.toChatGroup(LB.HELPER.MSG.getGameEvent("player_die_cause_unknown",srv,mobname))
            }
        break;

        case "runcmdfeedback":{
            let online_rgx = new RegExp(/(There are )(.*)\/(.*)( players online:)(\n.*|)/,'g')
            
            if(result == result.match(online_rgx)){
                var online = result.replace(online_rgx,"$2")
                var max = result.replace(online_rgx,"$3")
                var players = result.replace(online_rgx,"$5")
                if (players == ""){var players = "无"}
                LB.bot.toMgmtGroup(LB.HELPER.MSG.getRuncmdEvent("get_online_players",online,max,players))
                return
            }
            else if(result == "No targets matched selector"){
                LB.bot.toMgmtGroup(LB.HELPER.MSG.getRuncmdEvent("targets_not_found"))
                return
            }
            
            LB.bot.toMgmtGroup(LB.HELPER.MSG.getRuncmdEvent("runcmd_succeed")+"\n"+result)
        }
        break;

        case "server_info":
            let server_name = data.params.server_name
            let level_name = data.params.level_name
            let gamemode = data.params.gamemode
            let difficulty = data.params.difficulty
            let server_port = data.params.server_port
            let version = data.params.version
            LB.bot.toMgmtGroup(LB.HELPER.MSG.getGroupEvent("server_info_get",server_name,level_name,gamemode,difficulty,server_port,version))
        break;

        case "decodefailed":
            LB.bot.toMgmtGroup('数据包解析失败，请前往后台查看');
            LB.log.warn("数据包解析失败：",data.params.msg)
        break;
/*
        case "start":{
            LB.log.info("服务器已启动");
            LB.bot.toMgmtGroup('服务器 '+srv+' 已启动');
        };
        break;

        case "stop":{
            LB.log.info("服务器已关闭");
            LB.bot.toMgmtGroup('服务器 '+srv+' 已关闭');
        };
        break;
*/
        case "plantext":{};break;
    }
}

LB.MAIN.WEBSOCKET.push(ws_pre_proc)